package datas
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	import flash.media.Video;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.system.LoaderContext;
	
	import mx.controls.Alert;
	
	/**
	 * Import 되는 파일 대상 정렬
	 * @author hanjd
	 * 
	 */	
	public class LibraryItem extends EventDispatcher
	{
		// 중복되는 이름을 피하기 위해
		private static var _cursorPublishFileName: int = 0;
		// publish 저장될시 사용되는 파일명 > 한글 충돌 때문
		private var _publishFileName: String = null;
		
		
		// 원본 파일 대상
		private var _source: File;
		// 참조 카운트 : 몇번 사용되었는가?
		private var _retainCount: int;
		
		
		// 가상의 객체들
		private var _dummyObject: Object;
		
		// 컨텐츠 정보
		private var _contentInfo: ContentInfo;
		public function get contentInfo(): ContentInfo
		{
			return this._contentInfo;
		}
		/**
		 * 생성자 
		 * @param source
		 * 
		 */		
		public function LibraryItem()
		{
			super( this );
		}
		
		public function setFile(  source: File ): void
		{
			
			this._source 			= source;
			this._retainCount		= 0;
			
			this._publishFileName	= "item_"+(_cursorPublishFileName)+"."+this._source.extension.toLowerCase();
			_cursorPublishFileName++;
			
			// 컨텐츠 정보 긁어놓기
			if( this.type == LibraryItemType.IMAGE.name || this.type == LibraryItemType.SWF.name )
			{
				this._source.addEventListener( Event.COMPLETE, onFileDataLoadComplete );
				this._source.load();
				
			}else if( this.type == LibraryItemType.VIDEO.name )
			{
				this._dummyObject = {};
				
				var _nc: NetConnection = new NetConnection();
				_nc.connect( null );
				
				var _ns: NetStream	= new NetStream( _nc );
				_ns.client = {};
				_ns.client.onMetaData = this.onVideoMetaData;
				
				var _video: Video	= new Video();
				_video.attachNetStream( _ns );
				_ns.play( this._source.url );
				
				this._dummyObject._nc = _nc;
				this._dummyObject._ns = _ns;
				this._dummyObject._video = _video;
			}else{
				this.dispatchEvent( new Event( Event.COMPLETE ) );
			}
		}
		
		private function onFileDataLoadComplete( e: Event ): void
		{
			this._source.removeEventListener( Event.COMPLETE, onFileDataLoadComplete );
			
			var loaderContext: LoaderContext = new LoaderContext();
			loaderContext.allowLoadBytesCodeExecution = true; 
			
			var _loader: Loader 			= new Loader();
			_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onDisplayObjectLoadComplete );
			_loader.loadBytes( this._source.data, loaderContext );
		}
		
		private function onDisplayObjectLoadComplete( e: Event ): void
		{
			trace( "LibraryItem . onDisplayObjectLoadComplete()" );
			var info: LoaderInfo	= e.target as LoaderInfo;
			info.removeEventListener( Event.COMPLETE, onDisplayObjectLoadComplete );
			
			if( this.type == LibraryItemType.IMAGE.name )
			{
				this._contentInfo			= new ContentInfo( info.width, info.height, 0, null );
			}else{
				if( info.actionScriptVersion < 3 )
				{
					Alert.show( "현재 Actionscript 3.0 이상으로 제작된 SWF 파일만 가능합니다." );
					this._source.data.clear();
					this.dispatchEvent( new Event( Event.CANCEL ) );
					return;
				}
				
				this._contentInfo			= new ContentInfo( info.width, info.height, info.frameRate, String( info.actionScriptVersion ) );
			}
			
			this.dispatchEvent( new Event( Event.COMPLETE ) );
		}
		
		private function onVideoMetaData( info: Object ): void
		{
			trace( "LibraryItem . onVideoMetaData()" );
			for( var _key: String in info )
			{
				trace( _key, ":", info[ _key ] );
			}
			
			this._contentInfo				= new ContentInfo( info.width, info.height, info.videoframerate, null );
			
			var _nc: NetConnection 	= this._dummyObject._nc as NetConnection;
			var _ns: NetStream			= this._dummyObject._ns as NetStream;
			var _video: Video				= this._dummyObject._video as Video;
			
			_video.clear();
			_nc.close();
			_ns.dispose();
			
			delete this._dummyObject._nc;
			delete this._dummyObject._ns;
			delete this._dummyObject._video;
			
			this.dispatchEvent( new Event( Event.COMPLETE ) );
		}
		
		// 유형 반환
		public function get type(): String
		{
			return LibraryItemType.getType( this._source );
		}
		
		// 이름
		public function get name(): String
		{
			return this._source.name;
		}
		// 파일명
		public function get publishFileName(): String
		{
			return this._publishFileName;
		}
		
		// 파일의 정보
		public function toStringContentInfo(): String
		{
			var _info: Object			= {};
			_info[ "file_name" ]	= this._source.name;
			_info[ "type" ]			= this.type;
			
			// 사이즈
			_info[ "width" ]			= this._contentInfo.width;
			_info[ "height" ]			= this._contentInfo.height;
			
			if( this._contentInfo.frameRate != 0 ){
				_info[ "frameRate" ]	= this._contentInfo.frameRate;	
			}
			
			_info[ "version" ]		= this._contentInfo.version;
			
			var _str: String			= "";
			for( var _key: String in _info )
			{
				_str += _key+":"+_info[ _key ]+"\r";
			}
			return _str;
		}
		
		// 원본
		public function get source(): File
		{
			return this._source;
		}
		
		// 메모리 관리 및 유틸
		internal function retain(): void
		{
			this._retainCount++;
		}
		internal function release(): void
		{
			this._retainCount--;
		}
		public function get retainCount(): int
		{
			return this._retainCount;
		}
		
		// 파일 저장하기
		public function publish(): void
		{
			FileManager.saveToResourcePath( this );
		}
		
	}
}